import {
  Body,
  Controller,
  Delete,
  Get,
  Header,
  ParseIntPipe,
  Post,
  Put,
  Query,
  Res,
  UploadedFile,
  Param,
} from '@nestjs/common'
import { ArticleService } from './article.service'
import { CreateArticleDto } from './dto/create-article.dto'
import { UpdateArticleDto } from './dto/update-article.dto'
import { query, Response } from 'express'
import { Auth, fileMimetypeFilter, upload } from '@/decorators'
import { queryArticleDto } from '@/article/dto/query-article.dto'

@Controller('article')
export class ArticleController {
  constructor(private readonly articleService: ArticleService) {
  }

  @Post()
  create(@Body() createArticleDto: CreateArticleDto) {
    return this.articleService.create(createArticleDto)
  }

  @Get()
  @Auth()
  findAll(@Query() query: queryArticleDto) {
    console.log(query, 'query')
    return this.articleService.findAll(query)
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.articleService.findOne(+id)
  }

  @Put(':id')
  update(@Param('id') id: string, @Body() updateArticleDto: UpdateArticleDto) {
    return this.articleService.update(+id, updateArticleDto)
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.articleService.remove(+id)
  }

  @Post('export')
  @Header('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
  @Header('Content-Disposition', `attachment; filename=${encodeURIComponent('文章列表.xlsx')}`)
  async export(@Res() res: Response) {
    const buffer = await this.articleService.export()
    res.send(buffer)
  }

  @Post('import')
  @upload('file', {
    fileFilter: fileMimetypeFilter('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
  })
  import(@Body('categoryId', ParseIntPipe) categoryId: number, @UploadedFile() file: Express.Multer.File) {
    return this.articleService.import(categoryId, file)
  }
}
